package com.orhon.smartcampus.modules.student.mutation;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.GradesDao;
import com.orhon.smartcampus.modules.base.entity.Grades;
import com.orhon.smartcampus.modules.student.dao.ArrivesDao;
import com.orhon.smartcampus.modules.student.dao.EclassDao;
import com.orhon.smartcampus.modules.student.entity.Arrives;
import com.orhon.smartcampus.modules.student.entity.Eclass;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class UpgradeSchoolYearMutation implements DataFetcher {

    @Autowired
    private ArrivesDao arrivesDao;

    @Autowired
    private EclassDao eclassDao;

    @Autowired
    private GradesDao gradesDao;

    @Override
    @Transactional(readOnly = false)
    public Object get(DataFetchingEnvironment environment) throws Exception {

        List<Integer> arrive_ids = environment.getArgument("arrive_ids");
        for (Integer i : arrive_ids) {
            Long id = Long.valueOf(i);
            Arrives arrive;
            try {
                arrive = arrivesDao.findById(id);
                DetachedCriteria criteria = DetachedCriteria.forClass(Eclass.class);
                criteria.add(Restrictions.isNull("deletedAt"));
                criteria.add(Restrictions.eq("studentArrivesByArrivesId", arrive));
                List<Eclass> eclass = (List<Eclass>) eclassDao.findByCriteria(criteria);
                eclass.forEach(ec -> {
                    Long grade_id =ec.getBaseGradesByGradeId().getId();
                    if (grade_id == 6 || grade_id == 9 || grade_id == 12) {
                        try {
                            Grades grades = gradesDao.findById(0L);
                            ec.setBaseGradesByGradeId(grades);
                            eclassDao.update(ec);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else {
                        try {
                            Grades grades = gradesDao.findById(grade_id+1);
                            ec.setBaseGradesByGradeId(grades);
                            eclassDao.update(ec);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.ok();
    }
}
